package quartz;

/**
 * @Auther: cty
 * @Date: 2020/1/9 6:40
 * @Description: quartz学习入门（高级任务定时方法）
 * @version: 1.0
 */

import static org.quartz.DateBuilder.evenSecondDateAfterNow;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class QuartzTest {

    public void run() throws Exception {
        Logger log = LoggerFactory.getLogger(QuartzTest.class);

        log.info("------- Initializing ----------------------");

        // 1、创建Scheduler的工厂
        SchedulerFactory sf = new StdSchedulerFactory();
        // 2、从工厂中获取调度器
        Scheduler sched = sf.getScheduler();
        // 3、创建JobDetail
        JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();

        // 时间：下一秒
        Date runTime = evenSecondDateAfterNow();
        // 4、触发条件
        // 下一秒运行
//        Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
        // 下一秒运行，之后每隔5秒运行一次，再运行3次（共运行4次）
        Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime)
                .withSchedule(simpleSchedule().withIntervalInSeconds(5).withRepeatCount(3)).build();

        // 5、注册任务和触发条件
        sched.scheduleJob(job, trigger);
        // 6、启动
        sched.start();

        try {
            // 暂停20秒后停止线程
            Thread.sleep(20L * 1000L);
            // executing...
        } catch (Exception e) {
        }
        // 关闭调度器
        sched.shutdown(true);
    }

    public static void main(String[] args) throws Exception {

        QuartzTest example = new QuartzTest();
        example.run();

    }

}
